var tableID = "tableQuestionDetail"; //表格ID

$(function() {

	initTable();

	// 绑定问题类型
	bindDict("questionType", "question_item", "");
	
	// 点击新增
	$('#addQuestionDetail').click(function() {
		var num = $('#tableQuestionDetail').bootstrapTable('getOptions').totalRows;
		$('#title2').html("新增问题");
		$("#modalMenu2").modal('show');
		$('#num').html(num + 1);
	});

	//保存数据事件
	$('#save2').click(function() {
		var questionData = {};
		questionData.QUESTIONORDER = $("#num").html();
		questionData.QUESTIONNAIREID = $("#pk").val();
		questionData.QUESTION = $("#question").val();
		questionData.QUESTIONTYPE = $("#questionType").val();
		questionData.QUESTIONITEM = $("#questionItem").val();
		if (!check('attach')){
			return true;
		}
		var questionId = $("#questionId").val();
		if (questionId == "") {
			$.ajax({
				method : 'post',
				url : projectPath + 'question/insertq.do',
				data : JSON.stringify(questionData),
				dataType : "json",
				contentType : "application/json",
				success : function(data) {
					if (data.result == 1) {
						$('#tableQuestionDetail').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
						$('#modalMenu2').modal('hide');
					}
				}
			});
		} else {
			questionData.QUESTIONID = questionId;
			$.ajax({
				method : 'post',
				url : projectPath + 'question/updateq.do',
				data : JSON.stringify(questionData),
				dataType : "json",
				contentType : "application/json",
				success : function(data) {
					if (data.result == 1) {
						$('#tableQuestionDetail').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
						$('#modalMenu2').modal('hide');
					}
				}
			});
		}
	});

	$('#qst').change(function(){
		if('' != $('#qen').val()){
			if(Date.parse($('#qst').val()) > Date.parse($('#qen').val())){
				$('#qen').val('');
			}
		}
		$('#qen').attr('min', $('#qst').val());
	});
	
	//清空表单数据事件
	$("#modalMenu2").on("hidden.bs.modal", function() {
		clearForm();
	});
});


function init(pk, operator) {
	var da={};
	da.QUESTIONNAIREID = pk;
	da.pageNum="1";
	da.pageSize="1";
	$.ajax({
		type:"post",
		url: basePath() + 'question/list.do',
		data:JSON.stringify(da),
		dataType: "json",
		contentType : 'application/json;charset=UTF-8',
		success: function(data){	
			$("#pk").val(data.rows[0].QUESTIONNAIREID);
			$("#questionnaireTitle").val(data.rows[0].QUESTIONNAIRETITLE);
			$('#qst').val(data.rows[0].EFFECTIVESTARTDATE);
			$('#qen').val(data.rows[0].EFFECTIVEENDDATE);
			$("#disc").val(data.rows[0].QUESTIONNAIREDISC);
			$("[name='STATUS'][value='" + parseInt(data.rows[0].STATUS) + "']").prop("checked", true);
		}
	});
}

function initTable() {
	//获取主键
	var queryString = window.parent.document.getElementById("ifModal").contentWindow.location.search.substring(1);
	var param = parseQueryString(queryString);
	
	init(param.pk, param.operator);
	
	$('#tableQuestionDetail').bootstrapTable({
		method : 'post',
		url : projectPath + 'question/qlist.do',
		pagination : false, //分页
		dataType : "json",
		contentType : "application/json",
		striped : true, //是否显示行间隔色
		sidePagination : "server",
		////查询参数,每次调用是会带上这个参数，可自定义                         
		queryParams : function(params) {
			if (param.pk == '') {
				param.pk = '-';
			}
			return {
				pageNum : 1,
				pageSize : 999,
				QUESTIONNAIREID : param.pk
			};
		},
		columns : [ {
			field : 'number',
			title : '序号',
			align : 'center',
			width : '80px',
			formatter : function(value, row, index) {
				return index + 1;
			}
		}, {
			field : 'QUESTIONID',
			visible : false
		}, {
			field : 'QUESTION',
			width : '300px',
			title : '问题'
		}, {
			field : 'QUESTIONTYPE',
			width : '100px',
			title : '问题类型',
			formatter : function(value, row, index) {
				if (value == "1") {
					return "单选";
				}
				if (value == "2") {
					return "多选";
				}
			}
		}, {
			field : 'QUESTIONITEM',
			title : '问题选项'
		}, {
			field : 'operate',
			title : '操作',
			align : 'center',
			width : '200px',
			events : operateEvents,
			formatter : operateFormatter
		} ]
	});
	
	if('detail' == param.operator){
		$("#questionnaireTitle").attr("readonly", "readonly");
		$("#disc").attr("readonly","readonly");
		$("#qst").attr("readonly","readonly");
		$("#qen").attr("readonly","readonly");
		$("[name = 'STATUS']").attr("disabled","disabled");
		$("#addQuestionDetail").addClass("hidden");
		$("#save").addClass("hidden");
		$('#tableQuestionDetail').bootstrapTable('hideColumn', 'operate');
	}
}

function operateFormatter(value, row, index) {
	return [
			'<button type="button" class="Edit2 btn btn-warning  btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-edit"></span>编辑</button>',
			'<button type="button" class="Delete2 btn btn-danger  btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-minus"></span>删除</button>' 
		   ].join('');
}

window.operateEvents = {
	'click .Edit2' : function(e, value, row, index) {
		var questionTypeValue = parseInt(row.QUESTIONTYPE) < 10 ? "0" + parseInt(row.QUESTIONTYPE) : row.QUESTIONTYPE + "";
		$('#title2').html("修改问题");
		$("#modalMenu2").modal('show');
		$("#questionId").val(row.QUESTIONID);
		$("#question").val(row.QUESTION);
		$("#num").html(row.QUESTIONORDER);
		$("#questionType [value=" + questionTypeValue + "]").prop("selected", true);
		$("#questionItem").tagsinput('add', row.QUESTIONITEM);
	},
	'click .Delete2' : function(e, value, row, index) {
		var questionId = row.QUESTIONID;
		window.wxc.xcConfirm('是否<strong>删除</strong>序号[' + (index+1) + ']的数据?', window.wxc.xcConfirm.typeEnum.confirm,{
			onOk:function(v){
				$.ajax({
					url : projectPath + 'question/deleteq.do',
					data : {
						"QUESTIONID" : questionId
					},
					dataType : "json",
					success : function(data) {
						if (data.result == 1) {
							$('#tableQuestionDetail').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
						}
					}
				});
			}
		});
	}
};

//保存数据事件
function save(){
	var questionData = {};
	questionData.QUESTIONNAIREID = $("#pk").val();
	questionData.QUESTIONNAIRETITLE = $("#questionnaireTitle").val();
	questionData.QUESTIONNAIREDISC = $("#disc").val();
	questionData.EFFECTIVESTARTDATE = $("#qst").val();
	questionData.EFFECTIVEENDDATE = $("#qen").val();
	questionData.STATUS = $("input[name='STATUS']:checked").val();
	console.log(questionData);
	if (!check('main')){
		return true;
	}
	var questionDetailDatas = $('#tableQuestionDetail').bootstrapTable('getData');
	if(questionDetailDatas.length == 0){
		window.wxc.xcConfirm('请添加问卷问题', window.wxc.xcConfirm.typeEnum.error);
		return;
	}
	$.ajax({
		method : 'post',
		url : basePath() + 'question/update.do',
		data : JSON.stringify(questionData),
		dataType : "json",
		contentType : "application/json",
		success : function(data) {
			if (data.result == 1) {
				parent.closeModal('modalMenu');		//刷新数据
			}
		}
	});

}

/**
 * 获取get请求参数 (e.g. ?param1=value&parm2=...).
 */
function parseQueryString(query) {
    var parts = query.split('&');
    var params = {};
    for (var i = 0, ii = parts.length; i < ii; ++i) {
        var param = parts[i].split('=');
        var key = param[0].toLowerCase();
        var value = param.length > 1 ? param[1] : null;
        params[decodeURIComponent(key)] = decodeURIComponent(value);
    }
    return params;
}

function check(filedContent) {
	var result = true;
	var mustStr = "";
	if('main' == filedContent) {
		mustStr = "QUESTIONNAIRETITLE,QUESTIONNAIREDISC,EFFECTIVESTARTDATE,EFFECTIVEENDDATE";
	} else {
		mustStr = "QUESTION,QUESTIONTYPE,QUESTIONITEM";
	}
	var strMsg = "";
	var mustStrs = mustStr.split(',');
	for (var i = 0; mustStr != '' && i < mustStrs.length; i++) {
		var obj = $('[name="' + mustStrs[i] + '"]');
		var obj1 = obj.attr("placeholder");
		if (obj.val() == "") {
			strMsg += obj1.substring(0, 3)
					+ "<span style='color:red;'><strong>"
					+ obj1.substring(3, obj1.lengh) + "</strong></span>！<br />";
			result = false;
		}
	}
	if (strMsg != "") {
		window.wxc.xcConfirm(strMsg, window.wxc.xcConfirm.typeEnum.error);
	}
	return result;
}

function clearForm(){
	$("#questionType option:first").prop("selected", true);
	$("#questionId").val("");
	$("#question").val("");
	$("#num").html("");
	var items = $('#questionItem').val();
	if (items.indexOf(",") == -1) {
		$("#questionItem").tagsinput('remove', items);
	} else {
		var a = [];
		a = items.split(",");
		for (var i = 0; i < a.length; i++) {
			var item = a[i];
			$("#questionItem").tagsinput('remove', item);
		}
	}
}